#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stdvm.c"
int main(int argc, char** argv) {
	FILE* disk = fopen(argv[1], "rb+");
	if (disk == NULL) {
		perror("Error reading disk");
		return 1;
	}
	FILE* hard = fopen("volume.disk", "wb+");
	fseek(disk, 0, SEEK_END);
	long disksize = ftell(disk);
	rewind(disk);
	if (disksize < 512) {
		printf("Can't read disk:the MBR is very short\nFormat disk!\n");
		for(int i=0;i<1024;i++){
			fputc(0x00, disk);
		}
		return 1;
	}
	
	char* memory = (char*)malloc(1024000);
	char boot[512];
	fread(boot, 1, 512, disk);
	if (boot[0] != 0x61){
		printf("can't boot! os not found\n");
		printf("%x", boot[1]);
		free(memory);
		return 1;
	}
	for(int ptr=1;ptr<512;){
		int bc = boot[ptr];
		int arc = boot[ptr + 1];
		unsigned char args[512];
		int count = 0;
		for(int i=2;i<arc+2;i++){
			args[count] = boot[ptr + i];
			count++;
		}
		ptr+=arc;
		ptr+=2;
		int status = execute(bc, args, memory, hard);
		switch (status) {
			case 1:
				printf("Error Boot\n");
				break;
			case 2:
				printf("Fatal:Div by zero\n");
				break;
			case 3:
				ptr = 1;
				break;
			case 4:
				printf("shutdown");
				
				return 0;
			default:
				//TODO
				break;
		}
		
		
	}
	free(memory);
}
